package com.zx.framework.web.config;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.apache.log4j.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;

@Order(2)
public class AppContainerInitializer implements WebApplicationInitializer {
	
	private static final Logger LOGGER = Logger.getLogger(AppContainerInitializer.class);
	@Override
	public void onStartup(ServletContext servletContext)
			throws ServletException {
		if(LOGGER.isDebugEnabled()){
			LOGGER.debug("app init start!");
		}
		servletContext.setInitParameter("webAppRootKey", "base.root");
		servletContext.setInitParameter("contextConfigLocation", "classpath*:/applicationContext.xml");
		servletContext.addListener(org.springframework.web.context.ContextLoaderListener.class);
		servletContext.addListener(org.springframework.web.util.IntrospectorCleanupListener.class);
		
		FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", org.springframework.web.filter.CharacterEncodingFilter.class);
		encodingFilter.setInitParameter("encoding", "UTF-8");
		encodingFilter.addMappingForUrlPatterns(  
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/*");
		
		// 注册验证码
		ServletRegistration.Dynamic kaptchaDynamic = servletContext.addServlet(
				"Kaptcha", "com.google.code.kaptcha.servlet.KaptchaServlet");
		kaptchaDynamic.setInitParameter("kaptcha.border", "no");
		kaptchaDynamic.setInitParameter("kaptcha.textproducer.char.space", "8");
		kaptchaDynamic
				.setInitParameter("kaptcha.textproducer.char.length", "4");
		kaptchaDynamic.addMapping("/kaptcha");
	}
	
}
